import React, { useEffect, useState } from "react";
import {
  Space,
  Table,
  message,
  Popconfirm,
  Modal,
  Button,
  Form,
  Input,
  Select,
  DatePicker
} from "antd";
import axios from "axios";
import dayjs from "dayjs";
import { EditOutlined, DeleteOutlined,SearchOutlined } from "@ant-design/icons";
function List() {

  const [messageApi, contextHolder] = message.useMessage();
  const [name,setName]=useState('')
   const [date,setDate]=useState('')
  const [current,setCurrent]=useState('')
  const [total,setTotal]=useState('')
  const [pageSize,setPageSize]=useState('')
  //存储列表数据
  const [list, setList] = useState([]);
  //获取列表数据请求
  const getList = async () => {
    const res = await axios.get("http://localhost:4369/data",{params:{name,date,current,pageSize}});

    setList(res.data);
    setTotal(res.data.length)
  };
  useEffect(() => {
    getList();
  }, [name,date,current,pageSize]);
  

  //二次确认框删除
  const confirm = async (id) => {
    console.log(id);
    //删除请求
    await axios.delete(`http://localhost:4369/data/${id}`).then((res) => {
      console.log(res.data);
      messageApi.success("删除成功");
      getList();
    });
  };
  const cancel = (e) => {
    console.log(e);
    messageApi.error("删除失败");
  };

  //对话框
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [title,setTitle]=useState('')
  const [form]=Form.useForm()
  //新增按钮
  const showModal = () => {
    setIsModalOpen(true);
    setTitle('添加文章')
  };
  //确定按钮
  const handleOk = () => {
    setIsModalOpen(false);
    form.submit()
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };
//编辑按钮
const [editID,setEidtID]=useState('')
  const edit =(value)=>{
    setIsModalOpen(true);
    setTitle('编辑文章')
    //回显数据
    form.setFieldsValue(value)
    setEidtID(value.id)
  }

  const onFinish =async (values) => {
    //获取本地时间 并格式化
     const newDate = dayjs(new Date()).format('YYYY-MM-DD ')
     const newValues = {...values,date:newDate} //把时间带到数据里面 自动生成添加
     if(title==='添加文章'){
       //新增请求
        await axios.post('http://localhost:4369/data',newValues).then(res=>{
          console.log(res.data)
          messageApi.success('添加成功')
          getList()
        })
     }else{
          //编辑请求
        await axios.put(`http://localhost:4369/data/${editID}`,newValues).then(res=>{
          console.log(res.data)
          messageApi.success('修改成功')
          getList()
        })
     }
  };

  //搜索
  const [serarchValue]=Form.useForm()
  const Finish=(values)=>{
   setName(values.name)
   setDate(dayjs(values.date).format('YYYY-MM-DD'))
  }
  

 

  //分页
  const changeNum=(pageNum,pageSize)=>{
    setCurrent(pageNum)
    setPageSize(pageSize)
  }

  const columns = [
    {
      title: "ID",
      dataIndex: "id",
      key: "id",
    },
    {
      title: "小说名称",
      dataIndex: "name",
      key: "name",
      render: (text) => <a>{text}</a>,
    },
    {
      title: "小说类型",
      dataIndex: "type",
      key: "type",
    },
    {
      title: "排序",
      dataIndex: "num",
      key: "num",
    },
    {
      title: "描述",
      dataIndex: "address",
      key: "address",
    },
    {
      title: "加入时间",
      dataIndex: "date",
      key: "date",
      render:(text)=> dayjs(text).format('YYYY-MM-DD')
    },
    {
      title: "状态",
      dataIndex: "state",
      key: "state",
      render: (text) =>
        text === 1 ? (
          <span style={{ background: "skyblue", color: "#fff" }}>已启用</span>
        ) : (
          <span style={{ background: "orange", color: "#fff" }}>已禁用</span>
        ),
    },

    {
      title: "操作",
      key: "action",
      render: (record) => (
        <Space size="middle">
          <a onClick={()=>edit(record)}>
            <EditOutlined />
          </a>

          <Popconfirm
            title="删除系统"
            description="你确定要删除吗？"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="确定"
            cancelText="取消"
          >
            <a style={{ color: "red" }}>
              <DeleteOutlined />
            </a>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      {contextHolder}

         {/* 搜索表单 */}
        <Form
         form={serarchValue}
          name="basic"
          layout="inline"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 1200,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={Finish}
          autoComplete="off"
        >
          <Form.Item label="日期" name="date">
             <DatePicker  />
          </Form.Item>

          <Form.Item label="小说名称" name="name">
            <Input />
          </Form.Item>

          <Form.Item label={null}>
      <Button type="primary" htmlType="submit">
        <SearchOutlined/>
      </Button>
    </Form.Item>
        </Form>

      <div style={{display:'flex',justifyContent:'space-between'}}>
          <Button type="primary" onClick={showModal}>
        添加
      </Button>
        <h2>
          总共
        {total}条
      </h2>
      </div>
      {/* 表格和分页 */}
      <Table rowKey="id" columns={columns} dataSource={list}   
       pagination={
        {
           total:{total},
    showSizeChanger:true,
    showQuickJumper:true,
    showTotal:(total) => `Total ${total} items`,
    onChange:changeNum
        }
       }
      />;
      {/* 对话框 */}
      <Modal
        title="Basic Modal"
        open={isModalOpen}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {/* 弹框表单 */}
        <Form
        form={form}
          name="basic"
          labelCol={{
            span: 8,
          }}
          wrapperCol={{
            span: 16,
          }}
          style={{
            maxWidth: 600,
          }}
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
          autoComplete="off"
        >
          <Form.Item label="ID" name="id">
            <Input />
          </Form.Item>

          <Form.Item label="小说名称" name="name">
            <Input />
          </Form.Item>

          <Form.Item label="小说类型" name="type">
            <Input />
          </Form.Item>

          <Form.Item label="排序" name="num">
            <Input />
          </Form.Item>

          <Form.Item label="描述" name="address">
            <Input />
          </Form.Item>

          <Form.Item label="状态" name="state">
            <Select
             
              style={{
                width: 120,
              }}
              options={[
                {
                  value: 1,
                  label: "已启用",
                },
                {
                  value: 0,
                  label: "已禁用",
                },
              
              ]}
            />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}

export default List;
